package com.timbacsi.main;

import java.util.List;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.easycarebn.main.adapter.MenuHomeAdapter;
import com.easycarebn.main.fragment.FragmentAbout;
import com.easycarebn.main.fragment.FragmentAccountInfo;
import com.easycarebn.main.fragment.FragmentChangePass;
import com.easycarebn.main.fragment.FragmentContactus;
import com.easycarebn.main.fragment.FragmentForgetPass;
import com.easycarebn.main.fragment.FragmentHome;
import com.easycarebn.main.fragment.FragmentLogin;
import com.easycarebn.main.fragment.FragmentMessage;
import com.easycarebn.main.fragment.FragmentRegister;
import com.easycarebn.main.fragment.FragmentSearchResult;
import com.easycarebn.main.fragment.FragmentTab;
import com.easycarebn.main.menu.MenuDrawer;
import com.easycarebn.main.menu.MenuDrawer.OnDrawerStateChangeListener;
import com.easycarebn.main.menu.Position;
import com.easycarebn.main.model.ItemMeu;
import com.easycarebn.main.utils.IDataResponse;
import com.easycarebn.main.utils.IResult;
import com.easycarebn.main.utils.Utils;
import com.easycarebn.request.controller.ServerController;
import com.easycarebn.request.data.ContactInfoResponse;
import com.easycarebn.request.data.DataItemResponse;
import com.easycarebn.request.data.StatusCode;
import com.easycarebn.request.data.UserResponse;
import com.easycarebn.request.data.VersionApp;
import com.easycarebn.service.request.OnRequest;
import com.squareup.picasso.Picasso;

public class MainActivity extends SherlockFragmentActivity implements IResult {

	private MenuDrawer mLeftMenu;
	private MenuHomeAdapter mAdapter = null;
	private List<ItemMeu> mListMenu;
	private ListView mListViewMenu;
	private ProgressBar mLoadingMenu;
	private LinearLayout mLineAccount;
	private ImageView mAvata;
	private TextView mAccountName;
	private EasyCareApplication mEaApplication;

	private int mPostionClick = Integer.MAX_VALUE;
	private int mKeyOptionTask = Integer.MAX_VALUE;

	public static ProgressBar mLoadingData;
	public static Activity activity = null;
	private IDataResponse mDataResponse;
	public static boolean isPause = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		activity = MainActivity.this;
		/*AccountModel accountModel = Utils.getAccountModel(MainActivity.this,
				Utils.KEY_ACCOUNT_MODEL);
		if (accountModel != null) {
			Utils.requestLogin(MainActivity.this, this,
					accountModel.getUserName(), accountModel.getPassword(),
					false);
		}*/
		mEaApplication = (EasyCareApplication) getApplicationContext();

		getWindow().setBackgroundDrawableResource(R.color.green);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

		setContentView(R.layout.activity_main);
		addMenuLeft();
		addFragment(FragmentHome.newInstance(), Utils.TAG_HOME, false);

		mListViewMenu = (ListView) findViewById(R.id.menuView);
		mLoadingData = (ProgressBar) findViewById(R.id.loaddingData);
		View header = getLayoutInflater().inflate(R.layout.header_menu, null);
		mListViewMenu.addHeaderView(header);
		mListMenu = Utils.getMenu(MainActivity.this, R.menu.rightmenu_logout);

		mLeftMenu
				.setOnDrawerStateChangeListener(new OnDrawerStateChangeListener() {

					@Override
					public void onDrawerStateChange(int oldState, int newState) {
						Utils.hideKeyboard(MainActivity.this);
						if (newState == MenuDrawer.STATE_OPEN) {
							mLoadingMenu.setVisibility(View.GONE);
							setViewMenu();
						}

						if (newState == MenuDrawer.STATE_CLOSED) {
							clickMenu(mPostionClick);
						}

						getCountMessage();
					}
				});

		mListViewMenu.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				if (position == 0) {
					return;
				}

				mPostionClick = position - 1;
				mLeftMenu.closeMenu(true);

			}

		});
		mAvata = (ImageView) findViewById(R.id.avata);
		mAccountName = (TextView) findViewById(R.id.lblAccountName);
		setViewMenu();

	}

	public void setViewMenu() {
		if (mEaApplication.isLogin()) {
			setMenuControl();
			mEaApplication.setLogin(false);
		}

		if (mAdapter == null) {
			setMenuControl();
		}
	}

	public void checkUpdateApp() {
		// mLoadingData.setVisibility(View.VISIBLE);
		ServerController.getInstance(MainActivity.this).requestcheckUpgradeApp(
				"", new OnRequest<VersionApp>() {

					@Override
					public void onSuccess(VersionApp data) {
						mLoadingData.setVisibility(View.GONE);
						if (data == null)
							return;
						if (data.getCode() == StatusCode.OK) {
							PackageInfo pInfo = null;
							try {
								pInfo = getPackageManager().getPackageInfo(
										getPackageName(), 0);
							} catch (NameNotFoundException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							int version = pInfo.versionCode;
							if (data.getLastVersion() > version) {
								Utils.showDialogUpdate(activity, getResources()
										.getString(R.string.checkUpdate),
										new IResult() {

											@Override
											public void onDisplay(int arg1,
													String arg2) {
												if (arg1 == Activity.RESULT_OK) {
													Intent i = new Intent(
															android.content.Intent.ACTION_VIEW);
													i.setData(Uri.parse("https://play.google.com/store/apps/details?id="
															+ MainActivity.this
																	.getPackageName()));
													startActivity(i);
												}
											}
										});
							}
						}

					}

					@Override
					public void onError(int errorCode, String message) {
						mLoadingData.setVisibility(View.GONE);
					}
				});
	}

	@Override
	protected void onPause() {
		Log.d("onResume", "onResume");
		isPause = true;
	
		super.onPause();
	}

	@Override
	protected void onResume() {
		isPause = false;
		Log.d("onResume", "onResume");
		checkUpdateApp();
		super.onResume();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		switch (mKeyOptionTask) {
		case Utils.MAP_ALL_SEARCH_RESULT:
			menu.add(0, Utils.MAP_ALL_SEARCH_RESULT, Menu.NONE, "Map")
					.setIcon(R.drawable.ic_location_white)
					.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

			break;
		case Utils.MAP_CONTACT:
			menu.add(0, Utils.MAP_CONTACT, Menu.NONE, "Map")
					.setIcon(R.drawable.ic_location_white)
					.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

			break;
		default:
			menu.add(0, Integer.MAX_VALUE, Menu.NONE, "Add")
					.setIcon(android.R.color.transparent)
					.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

			break;
		}

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			if (isPageChild()) {

				Utils.hideKeyboard(MainActivity.this);
				addFragmentHome(FragmentHome.newInstance(), Utils.TAG_HOME);

			} else {
				mLeftMenu.openMenu();
			}

			break;
		case Utils.MAP_ALL_SEARCH_RESULT:
			if (FragmentSearchResult.newInstance("").getListDoctors() != null
					&& FragmentSearchResult.newInstance("").getListDoctors()
							.size() > 0)
				Utils.intentToDetailt(MainActivity.this,
						Utils.MAP_ALL_SEARCH_RESULT);

			break;
		case Utils.MAP_CONTACT:
			String location = "";
			String address = "";
			ContactInfoResponse data = FragmentContactus.newInstance("")
					.getContactInfoResponse();

			if (data == null || data.getMapPosition() == null) {
				return false;
			}
			location = data.getMapPosition().getLatitude() + ","
					+ data.getMapPosition().getLongtitude();

			if (data.getContactInfo() != null) {
				address = data.getContactInfo().getEasycare_address();
			} else {
				address = getResources().getString(R.string.dia_chi_easycare);
			}

			Utils.gotoMapContact(MainActivity.this, address, location);

			break;
		}
		return super.onOptionsItemSelected(item);
	}

	/* change view menu left */
	public void setMenuControl() {
		boolean isLogin;
		UserResponse user = Utils.getUserLogin(getApplicationContext());
		if (user != null && user.getUser() != null) {
			showAccInfo(user);
			isLogin = true;
		} else {
			showAccInfo(null);
			isLogin = false;
		}

		if (isLogin) {
			mListMenu = Utils
					.getMenu(MainActivity.this, R.menu.rightmenu_login);
			mAdapter = new MenuHomeAdapter(MainActivity.this, mListMenu);
			mListViewMenu.setAdapter(mAdapter);

		} else {
			addFragment(FragmentHome.newInstance(), Utils.TAG_HOME);
			mListMenu = Utils.getMenu(MainActivity.this,
					R.menu.rightmenu_logout);
			mAdapter = new MenuHomeAdapter(MainActivity.this, mListMenu);
			mListViewMenu.setAdapter(mAdapter);
		}
	}

	/* Add View Menu Left */
	public void addMenuLeft() {
		mLeftMenu = MenuDrawer.attach(this, MenuDrawer.MENU_DRAG_WINDOW,
				Position.LEFT);
		mLeftMenu.setDropShadowColor(Color.parseColor("#30e0e0e0"));
		mLeftMenu.setDropShadowSize(4);
		mLeftMenu.setAnimationCacheEnabled(true);
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		int width = displaymetrics.widthPixels;
		mLeftMenu.setMenuSize(5 * width / 6);
		mLeftMenu.setMenuView(R.layout.leftmenu);

		mLoadingMenu = (ProgressBar) findViewById(R.id.loadingMenu);

	}

	/* show account when login */
	public void showAccInfo(UserResponse userlogin) {
		mLineAccount = (LinearLayout) findViewById(R.id.lineAcc);
		if (userlogin != null && userlogin.getUser() != null) {
			mLineAccount.setVisibility(View.VISIBLE);
			mAccountName.setText(userlogin.getUser().getFullname());
			Picasso.with(MainActivity.this)
					.load(userlogin.getUser().getAvatar())
					.resize(Utils.IMG_WIDHT, Utils.IMG_HEIGHT)
					.placeholder(R.drawable.avata).error(R.drawable.avata)
					.into(mAvata);

			// mAvata.setImageUrl(userlogin.getUser().getAvatar(),
			// mImageLoader);
		} else {
			mLineAccount.setVisibility(View.GONE);
		}

		mLineAccount.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mPostionClick = 6;
				mLeftMenu.closeMenu(true);

			}
		});
	}

	/* Click Menu Event */
	public void clickMenu(int postion) {
		mKeyOptionTask = Integer.MAX_VALUE;
		if (mPostionClick == Integer.MAX_VALUE)
			return;

		int id = mListMenu.get(mPostionClick).getRegId();
		String title = mListMenu.get(mPostionClick).getTitle();

		switch (id) {
		case R.id.menu_trangchu:
			Log.d("menu_trangchu", "menu_trangchu");
			addFragment(FragmentHome.newInstance(), Utils.TAG_HOME);

			break;
		case R.id.menu_qlhk:

			addFragment(FragmentTab.newInstance(R.id.menu_qlhk, title),
					Utils.TAG_CHILD);

			break;
		case R.id.menu_tinnhan:
			addFragment(FragmentMessage.newInstance(title), Utils.TAG_CHILD);

			break;
		case R.id.menu_dangnhap:
			addFragment(FragmentLogin.newInstance(title), Utils.TAG_CHILD);

			break;
		case R.id.menu_yeuthich:

			addFragment(FragmentTab.newInstance(R.id.menu_yeuthich, title),
					Utils.TAG_CHILD);

			break;

		case R.id.menu_doimk:
			addFragment(FragmentChangePass.newInstance(title), Utils.TAG_CHILD);

			break;

		case R.id.menu_gioithieu:
			addFragment(FragmentAbout.newInstance(), Utils.TAG_CHILD);

			break;
		case R.id.menu_linehe:
			mKeyOptionTask = Utils.MAP_CONTACT;
			addFragment(FragmentContactus.newInstance(title), Utils.TAG_CHILD);

			break;
		case R.id.menu_qlttcn:
			addFragment(FragmentAccountInfo.newInstance(title), Utils.TAG_CHILD);

			break;

		case R.id.menu_dangki:
			Bundle bundle = new Bundle();
			bundle.putString(Utils.KEY_TITLE, title);
			bundle.putString(Utils.KEY_PHONE, "");

			addFragment(FragmentRegister.newInstance(bundle), Utils.TAG_CHILD);

			break;

		case R.id.menu_dangxuat:
			logout();

			break;

		}
		invalidateOptionsMenu();

		mPostionClick = Integer.MAX_VALUE;
	}

	/* logout */
	public void logout() {
		mEaApplication.setLogin(true);
		setMenuControl();
		onDisplay(Utils.SHOW_HOME, "");
		UserResponse user = Utils.getUserLogin(getApplicationContext());
		if (user == null || user.getToken().isEmpty()) {
			return;
		}
		ServerController.getInstance(getApplicationContext())
				.requestUserLogout(user.getToken(), GcmRegister.mGcmId,
						new OnRequest<DataItemResponse>() {

							@Override
							public void onSuccess(DataItemResponse data) {
								Utils.removeUserLogin(MainActivity.this);

								Utils.showMessage(
										MainActivity.this,
										getString(R.string.dang_xuat_thanh_cong));

							}

							@Override
							public void onError(int errorCode, String message) {
								Utils.showMessage(MainActivity.this, "");
							}
						});
	}

	public void addFragment(Fragment fragment, String tag, boolean isAnimation) {
		getSupportFragmentManager().beginTransaction()
				.replace(R.id.fragment_container, fragment, tag)
				.addToBackStack(null).commit();
	}

	/* Add page */
	public void addFragment(final Fragment fragment, final String tag) {
		new Handler().post(new Runnable() {
			public void run() {
				getSupportFragmentManager().beginTransaction()
						.replace(R.id.fragment_container, fragment, tag)
						.addToBackStack(null).commitAllowingStateLoss();
			}
		});

	}

	/* Add fragment Home */
	public void addFragmentHome(Fragment fragment, String tag) {
		getSupportFragmentManager().beginTransaction()
				.replace(R.id.fragment_container, fragment, tag)
				.addToBackStack(null).commit();
	}

	/* change taskbar */
	public void changeTaskbar(int icon, int bgr, int taskbar) {
		getSupportActionBar().setDisplayOptions(
				ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME);
		getSupportActionBar().setCustomView(taskbar);
		getSupportActionBar().setIcon(getResources().getDrawable(icon));
		getSupportActionBar().setBackgroundDrawable(
				getResources().getDrawable(bgr));
		getSupportActionBar().setHomeButtonEnabled(true);
		getSupportActionBar().setDisplayShowHomeEnabled(true);

	}

	/* check is page child */
	public boolean isPageChild() {
		Fragment fragment = getSupportFragmentManager().findFragmentByTag(
				Utils.TAG_CHILD);
		if (fragment == null)
			return false;
		return fragment.isVisible();
	}

	/* onBack click */
	public void onBack() {
		Log.d("Back_home", "Back_home");
		final int left = mLeftMenu.getDrawerState();
		if (left == MenuDrawer.STATE_OPEN || left == MenuDrawer.STATE_OPENING) {
			mLeftMenu.closeMenu();
			return;
		}
		if (isPageChild()) {

			Utils.hideKeyboard(MainActivity.this);
			addFragmentHome(FragmentHome.newInstance(), Utils.TAG_HOME);

		} else {
			finish();
		}
	}

	@Override
	public void onBackPressed() {
		onBack();
	}

	@Override
	public void onDisplay(int arg1, String arg2) {
		mLoadingData.setVisibility(View.GONE);

		switch (arg1) {
		case Utils.SHOW_HOME:
			Log.d("onDisplay", "onDisplay");
			addFragment(FragmentHome.newInstance(), Utils.TAG_HOME);
			setMenuControl();
			Utils.hideKeyboard(MainActivity.this);

			break;
		case Utils.TASK_HOME:
			// addViewSearch();
			mKeyOptionTask = Integer.MAX_VALUE;
			invalidateOptionsMenu();
			changeTaskbar(R.drawable.ic_menu, R.drawable.bgr_tasktop,
					R.layout.layout_taskbar);

			break;
		case Utils.TASK_CHILD:
			changeTaskbar(R.drawable.ic_back, R.drawable.bgr_tasktop_green,
					R.layout.layout_taskbar_children);

			break;

		case Utils.MAP_ALL_SEARCH_RESULT:

			addFragment(
					FragmentSearchResult.newInstance(getResources().getString(
							R.string.lblDanhsachbacsi)), Utils.TAG_CHILD);
			mKeyOptionTask = Utils.MAP_ALL_SEARCH_RESULT;
			invalidateOptionsMenu();

			break;
		case Utils.LOGIN:
			addFragment(FragmentLogin.newInstance(arg2), Utils.TAG_CHILD);

			break;
		case Utils.FORGET_PASS:
			addFragment(FragmentForgetPass.newInstance(arg2), Utils.TAG_CHILD);

			break;
		case Utils.CREATE_ACC:
			String array[] = arg2.split("-");
			Bundle bundle = new Bundle();
			bundle.putString(Utils.KEY_TITLE, array[0]);
			bundle.putString(Utils.KEY_PHONE, array[1]);
			addFragment(FragmentRegister.newInstance(bundle), Utils.TAG_CHILD);

			break;

		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		
		Log.d("requestCode",requestCode+"");
		if (resultCode == Activity.RESULT_CANCELED) {
			return;
		}

		if (requestCode == Utils.LOGIN_BOOKING) {
			UserResponse userResponse = Utils.getUserLogin(MainActivity.this);
			if (userResponse != null) {
				Utils.showMessage(MainActivity.this,
						getResources().getString(R.string.dang_nhap_thanh_cong));
				mEaApplication.setLogin(true);
				Utils.gotoBooking(MainActivity.this, FragmentSearchResult
						.newInstance("").getmDataBooking(), FragmentHome
						.newInstance().getSelectedSearchType());
			}
			return;
		}

		if (requestCode == Utils.REQ_EDIT_AVATAR) {
			FragmentAccountInfo.newInstance("").updateInfo(intent);
			return;

		}

		if (requestCode == Utils.REQ_ATTACH_FILE) {
			if (mDataResponse != null) {
				mDataResponse.onResult(requestCode, intent);
			}
		}
	}

	public void getCountMessage() {
		UserResponse user = Utils.getUserLogin(MainActivity.this);
		if (user == null)
			return;

		ServerController.getInstance(MainActivity.this)
				.requestNotificationCount(user.getToken(),
						new OnRequest<Integer>() {

							@Override
							public void onSuccess(Integer data) {
								for (int i = 0; i < mListMenu.size(); i++) {
									if (mListMenu.get(i).getRegId() == R.id.menu_tinnhan) {
										if (data > 0) {
											mListMenu.get(i).setNews(true);
											mListMenu.get(i).setCountNews(data);
										} else {
											mListMenu.get(i).setNews(false);
											mListMenu.get(i).setCountNews(0);
										}
										break;
									}
								}
								if (mAdapter != null)
									mAdapter.notifyDataSetChanged();
							}

							@Override
							public void onError(int errorCode, String message) {

							}
						});

	}

	public void setDataResponse(IDataResponse listener) {
		mDataResponse = listener;
	}

}
